package com.usts2022.classcostrecord;

import android.content.Context;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.usts2022.classcostrecord.Utils.HttpUtils;
import com.usts2022.classcostrecord.entity.User;

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.RequestBody;
import okhttp3.Response;


public class RegisterFragment extends Fragment {
    private Button mRegister;
    private EditText mAccount, mPassword, mName, mClassCode;
    private CheckBox mIsReporter,mIsCommittee;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_register, container, false);

        //绑定
        mRegister = view.findViewById(R.id.register);
        mAccount = view.findViewById(R.id.register_account);
        mPassword = view.findViewById(R.id.register_password);
        mName = view.findViewById(R.id.register_name);
        mClassCode = view.findViewById(R.id.register_class_code);
        mIsReporter = view.findViewById(R.id.register_check);
        mIsCommittee = view.findViewById(R.id.reg_is_class_com);

        //注册事件
        mRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String url = "/user/reg";
                User user = new User(mAccount.getText().toString(), mPassword.getText().toString(), mName.getText().toString(), Integer.parseInt(mClassCode.getText().toString()),mIsCommittee.isChecked() ? 1 : 0  ,mIsReporter.isChecked() ? 1 : 0);
                try {
                    HttpUtils.post(url, JSON.toJSONString(user), new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            if (Looper.myLooper() == null)
                                Looper.prepare();
                            Toast.makeText(getActivity(), "注册失败，网络错误", Toast.LENGTH_SHORT).show();
                            Looper.loop();
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            if (Looper.myLooper() == null)
                                Looper.prepare();
                            if (response.code()!= 200) {
                                Toast.makeText(getActivity(), "注册失败，网络错误", Toast.LENGTH_SHORT).show();
                            } else {
                                Toast.makeText(getActivity(), "注册成功,欢迎你！", Toast.LENGTH_SHORT).show();

                                //保存登录状态
                                saveData(mAccount.getText().toString(),mPassword.getText().toString());

                                getActivity().setResult(LoginFragment.LOGIN_RESULT_CODE);
                                getActivity().finish();
                            }
                            Looper.loop();
                        }
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        });

        return view;
    }


    public void saveData(String account, String password) {
        FileOutputStream out = null;
        BufferedWriter writer = null;
        String data = account + " " + password;
        try {
            //userName  表示文件的名称
            //MODE_APPEND 表示从文件后面接着写入，不会覆盖之前的数据
            //MODE_PRIVATE 表示会重新覆盖之前写入的数据
            out = getActivity().openFileOutput("loginData", Context.MODE_PRIVATE);
            writer = new BufferedWriter(new OutputStreamWriter(out));
            writer.write(data);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}